<template>
  <div class="contract-termination-page">
    <div class="wrap">
      <!-- 顶部步骤条 -->
      <StepBar :steps="steps" :current-step="2" />

      <div class="content">
        <!-- 左侧：基本信息、申请信息 -->
        <div class="left">
          <div class="card">
            <div class="card-title">基本信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="单据编号">{{ formData.elderlyNo }}</el-descriptions-item>
              <el-descriptions-item label="老人姓名">{{ formData.elderlyName }}</el-descriptions-item>
              <el-descriptions-item label="老人身份证号">{{ formData.elderlyIdCard }}</el-descriptions-item>
              <el-descriptions-item label="联系方式">{{ formData.contact }}</el-descriptions-item>
              <el-descriptions-item label="费用期限">{{ formData.feePeriod }}</el-descriptions-item>
              <el-descriptions-item label="护理等级">{{ formData.careLevel }}</el-descriptions-item>
              <el-descriptions-item label="入住床位">{{ formData.bedNumber }}</el-descriptions-item>
              <el-descriptions-item label="签约合同">
                {{ formData.contract }}
                <el-button link type="primary" size="small" style="margin-left: 8px" @click="viewContract">查看</el-button>
              </el-descriptions-item>
              <el-descriptions-item label="养老顾问">{{ formData.consultant }}</el-descriptions-item>
              <el-descriptions-item label="护理员">{{ formData.caregiver }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <div class="card">
            <div class="card-title">申请信息</div>
            <el-descriptions :column="2" border label-class-name="desc-label" class="desc">
              <el-descriptions-item label="退住日期">{{ formData.checkoutDate }}</el-descriptions-item>
              <el-descriptions-item label="退住原因">{{ formData.checkoutReason }}</el-descriptions-item>
              <el-descriptions-item label="备注" :span="2">
                {{ formData.remark }}
              </el-descriptions-item>
              <el-descriptions-item label="申请人">{{ formData.applicantName }}</el-descriptions-item>
              <el-descriptions-item label="申请时间">{{ formData.submitTime }}</el-descriptions-item>
            </el-descriptions>
          </div>

          <!-- 上传解除协议 -->
          <div class="card">
            <div class="card-title">
              <el-icon color="#f56c6c" style="vertical-align: middle; margin-right: 8px;">
                <WarningFilled />
              </el-icon>
              上传解除协议
            </div>
            <el-form label-width="100px">
              <el-form-item label="合同编号">
                <el-input v-model="contractForm.contractNo" placeholder="请输入" />
              </el-form-item>
              <el-form-item label="*解除日期">
                <el-date-picker
                  v-model="contractForm.terminationDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
              <el-form-item label="*解除协议">
                <el-upload
                  class="upload-demo"
                  :auto-upload="false"
                  :on-change="handleFileChange"
                  :file-list="fileList"
                  accept=".pdf,.doc,.docx"
                >
                  <el-button type="primary" plain>
                    <el-icon style="margin-right: 5px;"><Upload /></el-icon>
                    上传文件
                  </el-button>
                  <template #tip>
                    <div class="el-upload__tip">
                      请上传PDF文件，文件不超过10MB
                    </div>
                  </template>
                </el-upload>
              </el-form-item>
            </el-form>
          </div>
        </div>

        <!-- 右侧：操作记录 -->
        <div class="right">
          <div class="card">
            <div class="card-title">操作记录</div>
            <div class="timeline">
              <div class="timeline-item">
                <div class="timeline-icon success">✓</div>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <div class="timeline-title">发起申请-申请退住</div>
                    <div class="timeline-date">{{ formData.submitTime }}</div>
                  </div>
                  <div class="timeline-user">
                    {{ formData.applicantName }}
                    <el-tag size="small" type="success">已发起</el-tag>
                  </div>
                </div>
              </div>
              <div class="timeline-item">
                <div class="timeline-icon success">✓</div>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <div class="timeline-title">(待处理) 审批-申请审批</div>
                    <div class="timeline-date">2048-10-15 09:00:00</div>
                  </div>
                  <div class="timeline-user">
                    退住审批员
                    <el-tag size="small" type="success">已通过</el-tag>
                  </div>
                </div>
              </div>
              <div class="timeline-item">
                <div class="timeline-icon pending">⏱</div>
                <div class="timeline-content">
                  <div class="timeline-header">
                    <div class="timeline-title">(待处理) 审批-申请审批</div>
                  </div>
                  <div class="timeline-user">
                    退住审批员
                    <el-tag size="small" type="info">审批中</el-tag>
                  </div>
                  <div class="timeline-action">
                    <el-button type="primary" link @click="handleViewDetail">这是审批开始处，点此</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 底部操作按钮 -->
      <div class="bottom-actions">
        <el-button @click="handleBack">返回</el-button>
        <el-button type="primary" @click="handleSubmit">提交</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { WarningFilled, Upload } from '@element-plus/icons-vue'
import StepBar from '@/components/StepBar/index.vue'
import { getCheckoutApplicationDetail } from '@/api/system/approval'
import { getContractByElderlyId, submitTermination } from '@/api/system/out_management'
import { getTasksByBusinessIdAndStep } from '@/api/system/tasks'

const router = useRouter()
const route = useRoute()

// 步骤条数据
const steps = ['申请退住', '申请审批', '解除合同', '调整账单', '账单审批', '退住审批', '费用清算']

// 基本信息和申请信息数据
const formData = ref({
  elderlyNo: 'TZ204810101S000001',
  elderlyName: '高启强',
  elderlyIdCard: '230203197702221029',
  contact: '13898988888',
  feePeriod: '2048-10-10 —— 2049-10-10',
  careLevel: '特级护理等级',
  bedNumber: '101床位',
  contract: '高启强长住合同.pdf',
  consultant: '顾廷烨',
  caregiver: '盛长柏、盛明兰、盛如兰',
  checkoutDate: '2048-10-15',
  checkoutReason: '服务不周',
  remark: '已和家属沟通过，若高龄先生回归后，将重新办理入住',
  applicantName: '顾廷烨',
  submitTime: '2048-10-05 15:00:00'
})

// 表单数据
const contractForm = ref({
  contractNo: 'HT204810101S000001',
  terminationDate: new Date().toISOString().split('T')[0], // 设置为当前日期
  file: null
})

// 文件列表
const fileList = ref([])

// 页面加载时从URL参数查询业务数据
onMounted(async () => {
  console.log('=== 解除合同页面加载开始 ===')
  console.log('URL参数:', route.query)
  console.log('完整路由信息:', route)
  
  // ✅ 检查关键参数
  console.log('=== 关键参数检查 ===')
  console.log('业务ID (id):', route.query.id)
  console.log('任务ID (taskId):', route.query.taskId)
  console.log('待办任务ID (ptid):', route.query.ptid)
  
  if (!route.query.ptid) {
    console.warn('⚠️ 警告：ptid参数为空，将尝试自动查询第三步待办任务')
    
    // ✅ 自动查询第三步的待办任务
    if (route.query.id) {
      try {
        console.log('=== 自动查询第三步待办任务 ===')
        const response = await getTasksByBusinessIdAndStep(route.query.id, 3, 1) // type=1:退住申请
        console.log('查询第三步待办任务响应:', response)
        
        if (response.code === 200 && response.data) {
          const task = response.data
          console.log('✅ 找到第三步待办任务:', task)
          console.log('  任务ID:', task.taskId)
          console.log('  待办任务ID:', task.id)
          
          // 更新路由参数
          route.query.taskId = task.taskId
          route.query.ptid = task.id
          
          console.log('✅ 已更新路由参数')
          console.log('  新的taskId:', route.query.taskId)
          console.log('  新的ptid:', route.query.ptid)
        } else {
          console.error('❌ 未找到第三步待办任务:', response.msg)
        }
      } catch (error) {
        console.error('❌ 查询第三步待办任务失败:', error)
      }
    }
  }
  
  // 优先从后端API获取数据（根据业务ID查询）
  console.log('=== 优先从后端API获取数据 ===')
  
  if (route.query.id) {
    const businessId = route.query.id
    console.log('使用业务ID从后端获取数据:', businessId)
    
    try {
      const response = await getCheckoutApplicationDetail(businessId)
      console.log('后端返回的申请详情:', response)
      
      if (response.code === 200 && response.data) {
        const appData = response.data
        console.log('解析后的申请数据:', appData)
        
        // 使用后端数据更新表单
        formData.value = {
          elderlyNo: appData.checkOutNo || 'TZ' + businessId,
          elderlyName: appData.elderlyName || '未知老人',
          elderlyIdCard: appData.elderlyIdCard || '未知身份证',
          contact: appData.elderlyContact || '未知联系方式',
          feePeriod: (appData.feeStartDate && appData.feeEndDate) ? 
            `${appData.feeStartDate} —— ${appData.feeEndDate}` : '未知费用期限',
          careLevel: appData.careLevel || '未知护理等级',
          bedNumber: appData.bedNumber || '未知床位',
          contract: appData.contractName || '未知合同',
          consultant: appData.caregiverName || '未知顾问',
          caregiver: appData.caregiverName || '未知护理员',
          checkoutDate: appData.checkOutDate || '未知退住日期',
          checkoutReason: appData.checkOutReason || '未知退住原因',
          remark: appData.remark || '无备注',
          applicantName: appData.creatorName || '护理员a',
          submitTime: appData.createTime || new Date().toLocaleString('zh-CN', {
            year: 'numeric',
            month: '2-digit',
            day: '2-digit',
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
            hour12: false
          }).replace(/\//g, '-')
        }
        
        // 更新合同编号
        if (appData.contractNo) {
          contractForm.value.contractNo = appData.contractNo
          console.log('合同编号:', appData.contractNo)
        }
        
        console.log('使用后端数据更新表单:', formData.value)
        console.log('合同表单数据:', contractForm.value)
        
        // 如果有老人ID，尝试获取合同信息
        if (appData.elderlyId) {
          try {
            console.log('=== 获取合同信息 ===')
            console.log('老人ID:', appData.elderlyId)
            
            const contractResponse = await getContractByElderlyId(appData.elderlyId)
            console.log('合同API响应:', contractResponse)
            
            if (contractResponse.code === 200 && contractResponse.data) {
              console.log('合同数据:', contractResponse.data)
              if (contractResponse.data.contractName) {
                formData.value.contract = contractResponse.data.contractName
                console.log('合同名称:', contractResponse.data.contractName)
              }
              if (contractResponse.data.contractNo) {
                contractForm.value.contractNo = contractResponse.data.contractNo
                console.log('合同编号:', contractResponse.data.contractNo)
              }
            }
            
            console.log('=== 合同信息获取完成 ===')
          } catch (contractError) {
            console.error('获取合同信息失败:', contractError)
          }
        }
        
        console.log('=== 数据加载完成 ===')
        console.log('最终基本信息数据:', formData.value)
        console.log('最终合同表单数据:', contractForm.value)
      }
    } catch (apiError) {
      console.error('后端API调用失败:', apiError)
    }
  } else {
    console.log('警告：没有业务ID参数')
  }
  
  console.log('=== 解除合同页面加载完成 ===')
})

// 查看合同
const viewContract = () => {
  ElMessage.info('查看合同文件：高启强长住合同.pdf')
}

// 文件改变
const handleFileChange = (file, fileListParam) => {
  console.log('文件选择：', file)
  console.log('文件名：', file.name)
  contractForm.value.file = file
  // 更新文件列表
  fileList.value = fileListParam
}

// 查看详情
const handleViewDetail = () => {
  ElMessage.info('跳转到审批详情页面')
}

// 返回
const handleBack = () => {
  // 返回到待办任务列表
  router.push('/xtgz/xtgz/tasks')
}

// 提交
const handleSubmit = async () => {
  console.log('=== 开始提交解除合同 ===')
  
  // 验证必填项
  if (!contractForm.value.terminationDate) {
    ElMessage.warning('请选择解除日期！')
    return
  }

  if (fileList.value.length === 0) {
    ElMessage.warning('请上传解除协议！')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确认提交解除合同申请吗？',
      '确认提交',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    // 准备提交数据
    const fileName = fileList.value[0].name
    console.log('上传的文件名:', fileName)
    
    const submitData = {
      businessId: route.query.id, // 业务ID
      contractNo: contractForm.value.contractNo, // 合同编号
      fileName: fileName, // 文件名
      taskId: route.query.taskId || '', // 任务ID（步骤3的taskId）
      ptId: route.query.ptid || '' // ✅ 待办任务ID（需要删除的）
    }
    
    console.log('提交数据:', submitData)
    console.log('业务ID:', submitData.businessId)
    console.log('合同编号:', submitData.contractNo)
    console.log('文件名:', submitData.fileName)
    console.log('当前任务ID:', submitData.taskId)
    console.log('当前待办任务ID:', submitData.ptId)
    
    // ✅ 参数验证
    if (!submitData.ptId) {
      ElMessage.error('待办任务ID为空，无法提交！请检查页面参数。')
      console.error('❌ 提交失败：ptId参数为空')
      return
    }
    
    if (!submitData.businessId) {
      ElMessage.error('业务ID为空，无法提交！')
      console.error('❌ 提交失败：businessId参数为空')
      return
    }
    
    // 调用后端API提交
    const response = await submitTermination(submitData)
    
    console.log('提交响应:', response)
    
    if (response.code === 200) {
      ElMessage.success('解除合同已提交成功！')
      
      // 提交成功后跳转到下一步：账单调整
      // ✅ 需要传递第四步所需的参数
      setTimeout(() => {
        router.push({
          path: '/splccs/zdtz',
          query: {
            id: route.query.id, // 业务ID
            taskId: response.data?.nextTaskId || '', // 第四步的工作流任务ID
            ptid: response.data?.nextPtId || '', // 第四步的待办任务ID
            step: 4,
            type: route.query.type || 1
          }
        })
      }, 1000)
    } else {
      ElMessage.error('提交失败：' + (response.msg || '未知错误'))
    }
    
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消提交
      console.log('用户取消提交')
      return
    }
    console.error('提交异常:', error)
    ElMessage.error('提交失败：' + (error.message || '未知错误'))
  }
}
</script>

<style scoped lang="scss">
.contract-termination-page {
  min-height: 100%;
  background: linear-gradient(135deg, #e8f5e9 0%, #f1f8e9 50%, #fffde7 100%);
  padding: 20px;
  position: relative;
  overflow: hidden;

  // 装饰性背景元素
  &::before,
  &::after {
    content: '';
    position: absolute;
    border-radius: 50%;
    opacity: 0.3;
    pointer-events: none;
  }

  &::before {
    width: 400px;
    height: 400px;
    background: radial-gradient(circle, rgba(205, 220, 57, 0.3) 0%, transparent 70%);
    top: 100px;
    left: 10%;
  }

  &::after {
    width: 300px;
    height: 300px;
    background: radial-gradient(circle, rgba(139, 195, 74, 0.25) 0%, transparent 70%);
    top: 200px;
    right: 15%;
  }
}

.wrap {
  max-width: 1400px;
  margin: 0 auto;
  position: relative;
  z-index: 1;
}

/* 内容区域 */
.content {
  display: grid;
  grid-template-columns: 1fr 450px;
  gap: 20px;
  margin-bottom: 20px;
}

.left,
.right {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.card {
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 20px;
  padding-bottom: 12px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  align-items: center;
}

/* 描述列表样式 */
:deep(.desc) {
  .desc-label {
    background: #fafafa;
    color: #666;
    font-weight: normal;
    text-align: right;
  }
}

/* 表单样式 */
:deep(.el-form-item) {
  margin-bottom: 20px;
}

/* 上传组件样式 */
.upload-demo {
  width: 100%;
}

:deep(.el-upload__tip) {
  margin-top: 8px;
  font-size: 12px;
  color: #999;
}

/* 时间轴样式 */
.timeline {
  .timeline-item {
    display: flex;
    gap: 15px;
    margin-bottom: 25px;
    position: relative;

    &:last-child {
      margin-bottom: 0;
    }

    &:not(:last-child)::after {
      content: '';
      position: absolute;
      left: 21px;
      top: 45px;
      bottom: -25px;
      width: 2px;
      background: #e0e0e0;
    }
  }

  .timeline-icon {
    width: 42px;
    height: 42px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 16px;
    flex-shrink: 0;

    &.success {
      background: #67c23a;
    }

    &.pending {
      background: #409eff;
    }
  }

  .timeline-content {
    flex: 1;
    padding-top: 2px;
  }

  .timeline-header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    align-items: center;
  }

  .timeline-title {
    font-size: 14px;
    color: #333;
    font-weight: 500;
  }

  .timeline-date {
    font-size: 12px;
    color: #999;
    white-space: nowrap;
  }

  .timeline-user {
    font-size: 13px;
    color: #666;
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
  }

  .timeline-action {
    margin-top: 8px;
  }
}

/* 底部按钮 */
.bottom-actions {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .content {
    grid-template-columns: 1fr;
  }
}
</style>

